'use strict';

const Service = require('egg').Service;

class CommentService extends Service {
    /**
     * 查询评论
     *
     * @param {String} articleId    @default null    -文章id
     * @param {Number} page         @default 1       -当前页
     * @param {Number} currentPage  @default 30      -返回条数
     * @param {String} select       @default null    -要显示的key
     */
    async find({ articleId, page = 1, currentPage = 10 } = {}, select = null) {
        const { ctx } = this;
        const userpopulate = 'title headImg role username';

        const res = await ctx.model.Comment
            .find({ articleId, delete: false })
            .sort({ '_id': -1 })
            .skip((Number(page) - 1) * Number(currentPage))
            .limit(Number(currentPage))
            .populate('auth', userpopulate)
            .select(select);
        const count = await ctx.model.Comment
            .find({ articleId, delete: false })
            .count();
        return {
            count,
            page,
            list: res
        }
    }
    /**
     * 根据评论ID获取评论
     *
     * @param {String} id    @default null    -评论id
     * @param {String} select       @default null    -要显示的key
     */
    async findById(id, select = null) {
        const { ctx } = this;
        const userpopulate = 'title headImg role username';

        return await ctx.model.Comment
            .findById(id)
            .populate('auth', userpopulate)
            .select(select);
    }
    /**
     * 新增评论
     *
     * @param {String} articleId    -文章ID
     * @param {String} content      -评论内容
     */
    async create({ articleId, content } = {}) {
        const { ctx, app } = this;

        const article = await ctx.model.Article.findById(articleId);
        if (!article || article.delete) {
            ctx.throw(404, '文章不存在，无法评论');
        }

        content = app.linkUsers(content);
        const res = await ctx.model.Comment.create({
            articleId,
            content,
            auth: ctx.state.user._id
        });
        ctx.model.Article.findByIdAndUpdate(articleId, {
            $inc: { 'numbers.comment': 1 }
        }).then(res => {
            console.log('文章评论+1', res)
        })
        console.log('新增评论：', res);
        return res;
    }

    /**
     * 删除评论
     *
     * @param {String} id -评论ID
     */
    async destroy(id) {
        const { ctx } = this;

        const comment = await ctx.model.Comment.findById(id);
        if (!comment || comment.delete) {
            ctx.throw(404, '评论不存在');
        }
        // 权限验证
        await ctx.powerValidate(comment.auth._id);

        const res = await ctx.model.Comment.findByIdAndUpdate(id, {
            delete: true,
            updateAt: Date.now()
        });
        ctx.model.Article.findByIdAndUpdate(comment.articleId, {
            $inc: { 'numbers.comment': -1 }
        });
        return res;
    }

    /**
     * 点赞/取消点赞评论
     *
     * @param {String} id -评论ID
     */
    async userLikeComment(id) {
        const { ctx } = this;
        const isuser = await ctx.model.Comment.find({ '_id': id, 'likesUser': ctx.state.user._id });
        let res;
        if (isuser.length === 0) {
            res = await ctx.model.Comment.findByIdAndUpdate(id, {
                $addToSet: { 'likesUser': ctx.state.user._id },
                $inc: { 'numbers.like': 1 }
            });
            return {
                message: '点赞成功',
                action: 'up'
            }
        } else {
            res = await ctx.model.Comment.findByIdAndUpdate(id, {
                $pull: { 'likesUser': ctx.state.user._id },
                $inc: { 'numbers.like': -1 }
            });
            return {
                message: '取消点赞成功',
                action: 'down'
            }
        }
    }
}

module.exports = CommentService;
